package com.sjtu.servlet;

import com.sjtu.bean.UserBean;
import com.sjtu.constants.Constants;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

public class CheckUserServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doWork(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doWork(request, response);
    }

    public void doWork(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String obj = request.getParameter("obj");
        JSONObject jsonObj = null;
        String type = "";
        int userId = 0;
        try {
            jsonObj = new JSONObject(obj);
            type = jsonObj.getString("checkResult");
            userId = Integer.parseInt(jsonObj.getString("userId"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        PrintWriter writer = response.getWriter();
        if (type.equals("reject")) {
            UserBean.rejectUser(userId);
        } else {
            try {
                int score = Integer.parseInt(jsonObj.getString("score"));
                if (UserBean.checkUser(userId, score)) {
                    writer.write("Check User Successfully");
//                writer.write("another string");
                } else {
                    writer.write("Error occured");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        writer.flush();
        writer.close();
    }
}
